package cn.acewill.yxd.yunxundian.ui.schedule;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jimmy.common.listener.OnTaskFinishedListener;

import org.xutils.ex.DbException;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.componet.menology.OnCalendarClickListener;
import cn.acewill.yxd.yunxundian.componet.menology.schedule.ScheduleLayout;
import cn.acewill.yxd.yunxundian.componet.menology.schedule.ScheduleRecyclerView;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.addHolidayBean;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by XXX on 2017/5/27.
 */

public class ScheduleAddHoliday extends BaseActivity implements OnTaskFinishedListener<List<addHolidayBean>>{

    private TextView textTitle;
    private List<addHolidayBean> hList;
    //当前时间
    private int thisyear,thismonth,thisday;
    private ScheduleLayout slSchedule;
    //选中类型
    private String selectType=null;
    private ScheduleRecyclerView rvScheduleList;
    //当前休息的数据
    private List<Schedule> schRestList;
    //删除的scheduleid
    private int schId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.add_holiday_view);
        super.onCreate(savedInstanceState);
        initView();
        initRecycleView();
    }


    public void initRecycleView(){
        rvScheduleList = slSchedule.getSchedulerRecyclerView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this );
        rvScheduleList.setLayoutManager(layoutManager);
        layoutManager.setOrientation(OrientationHelper. VERTICAL);
    }

    public void initView(){
//        String[] jiaqi={"年假","休息","其他假"};
//        try {
//            schRestList=db.selector(Schedule.class).where("title","in",jiaqi).and("toUserId", "=", MainActivity.id).findAll();
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
        getCurrentdate();
        Button sureBtn = (Button) findViewById(R.id.sureBtn);
        sureBtn.setVisibility(View.GONE);
        this.textTitle= (TextView) findViewById(R.id.textTitle);
        int month=thismonth+1;
        this.rvScheduleList= (ScheduleRecyclerView) findViewById(R.id.rvScheduleList);
        if (month<10){
            this.textTitle.setText(thisyear+"年"+0+month+"月");
        }else{
            this.textTitle.setText(thisyear+"年"+month+"月");
        }
        RadioGroup mygroup = (RadioGroup) findViewById(R.id.mygroup);
        if (selectType==null){
            mygroup.check(R.id.radioRest);
            selectType="xiuxi";
        }
        mygroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId==R.id.radioRest){
                    selectType="xiuxi";
                }else if (checkedId==R.id.radioAnnual){
                    selectType="nianjia";
                }else{
                    selectType="qitajia";
                }
            }
        });

        this.slSchedule= (ScheduleLayout) findViewById(R.id.slSchedule);
        slSchedule.getMonthCalendar().setTodayToView();

        slSchedule.setOnCalendarClickListener(new OnCalendarClickListener() {
            @Override
            public void onClickDate(int year, int month, int day) {
                thismonth=month+1;
                thisyear=year;
                thisday=day;
                String tmonth=null;
                String tday=null;
                if (month<9){
                    int dmonth=month+1;
                    tmonth=0+""+dmonth;
                }else{
                    tmonth=thismonth+"";
                }
                if (day<10){
                    tday=0+""+thisday;
                }else{
                    tday=thisday+"";
                }
               textTitle.setText(year+"年"+tmonth+"月");
                String data=year+"-"+tmonth+"-"+day;
                hList=new ArrayList<addHolidayBean>();
                hList.add(new addHolidayBean(selectType,MainActivity.id,data));
               //是否存在
                checkHoliday(tmonth,tday);

            }
            @Override
            public void onPageChange(int year, int month, int day) {
                thismonth=month+1;
                thisyear=year;
                thisday=day;
                int tmonth=month+1;
                textTitle.setText("点击添加 "+year+"年"+tmonth+"月");
            }
        });
    }

    public void getCurrentdate() {
        Calendar c = Calendar.getInstance();
        thisyear = c.get(Calendar.YEAR);
        thismonth = c.get(Calendar.MONTH);
        thisday = c.get(Calendar.DAY_OF_MONTH);
    }


    public void checkHoliday(String month,String day){
        boolean flag=true;
        String[] jiaqi={"年假","休息","其他假"};
        try {
            schRestList=db.selector(Schedule.class).where("title","in",jiaqi).and("toUserId", "=", MainActivity.id).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (schRestList==null){
            showAnimaDialog(ScheduleAddHoliday.this,"请求出错啦！");
            return;
        }
        for (int i=0;i<schRestList.size();i++){
            String[] rest=schRestList.get(i).getSchStartTime().split("\\-|T");
            String a=rest[2];
            //判断是否存在，存在则删除。不存在则添加
            if (String.valueOf(thisyear).equals(rest[0])&&month.equals(rest[1])&&day.equals(rest[2])){
                //已经存在则提示删除，刷新页面
                flag=false;
                schId=schRestList.get(i).getID();
                break;
            }
        }
        if (flag){
            upLoadInfo();
        }else{
            MaterialDialogUtils.showMaterialDialog(this, "是否删除当前选中的假期", "确定", "取消", true,false
                    , new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            //删除数据,获取当前日期的休息日程
                            dialog.dismiss();
                            dropHoliday();
                        }
                    }, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    });
        }
    }
    public void upLoadInfo() {
        Map<String, Object> map = new HashMap<>();
        Gson gson = new Gson();
        map.put("empid", MainActivity.id);
        map.put("task", "addHoildayNew");
        map.put("holidayStr", gson.toJson(hList));
        pubClass.Post(this, pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] rearray = result.split("\\|");
                if (rearray[0].equals("200")) {
                    //此处更新日程的数据，然后重新加载数据
                    Gson gson=new Gson();
                    Type typeList=new TypeToken<ArrayList<Schedule>>(){}.getType();
                    ArrayList<Schedule> schedules=gson.fromJson(pubClass.convertToArrayJson(result),typeList);
                    try {
                        db.saveOrUpdate(schedules);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    updateSchedule();
                } else {
                    showAnimaDialog(ScheduleAddHoliday.this,rearray[1]);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    public void dropHoliday(){
        Map<String, Object> map = new HashMap<>();
        map.put("schid",schId);
        map.put("task", "delSchById");
        pubClass.Post(this,pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] array=result.split("\\|");
                if (array[0].equals("200")||result.equals("")){
                    showAnimaDialog(ScheduleAddHoliday.this,"删除成功");
                    try {
                        Schedule schedule=db.selector(Schedule.class).where("ID","=",schId).findFirst();
                        db.delete(schedule);

                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    updateSchedule();

                }else{
                    showAnimaDialog(ScheduleAddHoliday.this,array[1]);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                showAnimaDialog(ScheduleAddHoliday.this,"删除失败");
            }
        });
    }

    public void updateSchedule(){
        slSchedule.updateTask();
    }

    @Override
    public void onTaskFinished(List<addHolidayBean> data) {
        updateSchedule();
    }

}
